package com.ddstation.onsitelaw.service;


import com.ddstation.common.wx3th.property.Wx3thPlatformProperty;
import com.ddstation.onsitelaw.entity.WxAccessTokenEntity;
import com.ddstation.onsitelaw.entity.WxComponentVerifyTicketEntity;
import com.ddstation.onsitelaw.entity.WxDingtalkUserEntity;
import com.ddstation.onsitelaw.mapper.WxAccessTokenMapper;
import com.ddstation.onsitelaw.mapper.WxComponentVerifyTicketMapper;
import com.ddstation.onsitelaw.mapper.WxUserMapper;
import com.ddstation.onsitelaw.model.auditmodel.UserModel;
import com.ddstation.onsitelaw.utils.Constant;
import com.ddstation.onsitelaw.utils.CopyBeanUtil;
import com.ddstation.onsitelaw.utils.HttpClient;
import net.sf.json.JSONObject;
import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import javax.inject.Inject;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@Service
public class Wx3thPlatformServiceImpl implements Wx3thPlatformServiceItf {
    private static final Logger logger = LoggerFactory.getLogger(Wx3thPlatformServiceImpl.class);
    @Inject
    private WxComponentVerifyTicketMapper wxComponentVerifyTicketMapper;
    @Inject
    private WxAccessTokenMapper wxAccessTokenMapper;

    @Inject
    private WxUserMapper wxUserMapper;

    public String getSuiteKeyStr() {
        return "WEKNOW_ENTERPRISE_WECHATSUTIE";
    }

    public String getEnterpriseWeChatComponentVerifyTicket() {
        String componentVerifyTicket = null;
        WxComponentVerifyTicketEntity latelyOne = this.wxComponentVerifyTicketMapper.selectLatelyOne("WEKNOW_ENTERPRISE_WECHAT");
        if (latelyOne != null) {
            componentVerifyTicket = latelyOne.getComponentVerifyTicket();
        }

        return componentVerifyTicket;
    }

    @Override
    public String getEnterpriseWeChatSuiteAccessToken() {

        String suiteAccessTokenKey = this.getSuiteKeyStr();
        WxAccessTokenEntity entity = this.wxAccessTokenMapper.selectLatelyOne(suiteAccessTokenKey);
        if (entity != null) {
            return entity.getAccessToken();
        } else {
            String suiteTicket = this.getEnterpriseWeChatComponentVerifyTicket();
            if (suiteTicket == null) {
                throw new RuntimeException("getSuiteAccessToken出错，未取到suite_ticket,请先去企业微信后台刷新suite_ticket");
            } else {
                try {
                    String url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token";
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("suite_id", Constant.suiteId);
                    jsonObject.put("suite_secret", Constant.secret);
                    jsonObject.put("suite_ticket", suiteTicket);
                    String msg = HttpClient.sendPost(url, jsonObject, "utf-8");
                    JSONObject fromObject = JSONObject.fromObject(msg);
                    if (fromObject.get("errcode") != null && !"0".equals(fromObject.get("errcode").toString())) {
                        logger.info(msg);
                        throw new RuntimeException("获取企业微信suite_token失败！suite_ticket=" + suiteTicket + ",msg=" + msg);
                    } else {
                        WxAccessTokenEntity newEntity = new WxAccessTokenEntity();
                        newEntity.setAppId(suiteAccessTokenKey);
                        newEntity.setAccessToken(fromObject.get("suite_access_token").toString());
                        newEntity.setExpire(fromObject.getInt("expires_in"));
                        this.wxAccessTokenMapper.insert(newEntity);
                        List<WxAccessTokenEntity> list = this.wxAccessTokenMapper.selectGcTarget(suiteAccessTokenKey);
                        if (list != null) {
                            Iterator var10 = list.iterator();

                            while (var10.hasNext()) {
                                WxAccessTokenEntity gc = (WxAccessTokenEntity) var10.next();
                                this.wxAccessTokenMapper.delete(gc);
                            }
                        }

                        return newEntity.getAccessToken();
                    }
                } catch (ClientProtocolException var12) {
                    throw new RuntimeException(var12);
                } catch (IOException var13) {
                    throw new RuntimeException(var13);
                }
            }
        }
    }


    @Override
    public int refreshEnterpriseWeChatComponentVerifyTicket(String componentVerifyTicket) {
        if (logger.isDebugEnabled()) {
            logger.debug("刷新企业微信票据access token");
            logger.debug("componentVerifyTicket = " + componentVerifyTicket);
        }

        WxComponentVerifyTicketEntity entity = new WxComponentVerifyTicketEntity();
        entity.setAppId("WEKNOW_ENTERPRISE_WECHAT");
        entity.setComponentVerifyTicket(componentVerifyTicket);
        int newCnt = this.wxComponentVerifyTicketMapper.insert(entity);
        List<WxComponentVerifyTicketEntity> list = this.wxComponentVerifyTicketMapper.selectGcTarget(Wx3thPlatformProperty.getComponentAppID());
        if (list != null) {
            Iterator var5 = list.iterator();

            while (var5.hasNext()) {
                WxComponentVerifyTicketEntity gc = (WxComponentVerifyTicketEntity) var5.next();
                this.wxComponentVerifyTicketMapper.delete(gc);
            }
        }

        return newCnt;
    }

    @Override
    public Integer insertWxUserUUID(UserModel userModel) {
        WxDingtalkUserEntity wxUserEntity = CopyBeanUtil.copyObject(userModel, WxDingtalkUserEntity.class);
        wxUserMapper.insertSelective(wxUserEntity);
        return wxUserEntity.getId();
    }

    @Override
    public Integer selectWxUser(UserModel userModel) {
        Example example = new Example(WxDingtalkUserEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userModel.getUserId());
        criteria.andEqualTo("open_userid", userModel.getOpen_userid());
        List<WxDingtalkUserEntity> userEntityList = wxUserMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(userEntityList)) {
            return userEntityList.get(0).getId();
        }
        return -1;
    }
}
